const http = require("http");
const url = require("url");
const routes = [
  {
    path: "*",
    method: "*",
    handler(req, res) {
      res.end(`my Cannot ${req.method.toLowerCase()} ${req.url}`);
    },
  },
];
function createApplication() {
  return {
    get(path, handler) {
      routes.push({
        path,
        method: "get",
        handler,
      });
    },
    listen(...args) {
      const server = http.createServer((req, res) => {
        let { pathname } = url.parse(req.url);
        let requestMethod = req.method.toLowerCase();
        for (let i = 1; i < routes.length; i++) {
          let { path, method, handler } = routes[i];
          if (path === pathname && method === requestMethod) {
            return handler(req, res);
          }
        }
        routes[0].handler(req, res);
      });
      server.listen(...args);
    },
  };
}

module.exports = createApplication;
